import {finalize, tap} from 'rxjs/operators';
import {HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Zero3LayoutNavbarComponent} from '../zero3-layout-navbar/zero3-layout-navbar.component';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
    // constructor(private messenger: MessageService) {}

    constructor() {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const started = Date.now();
        let ok: string;

        // extend server response observable with logging
        return next.handle(req)
            .pipe(
                tap(
                    // Succeeds when there is a response; ignore other events
                    event => ok = event instanceof HttpResponse ? 'succeeded' : '',
                    // Operation failed; error is an HttpErrorResponse
                    error => ok = 'failed'
                ),
                // Log when response observable either completes or errors
                finalize(() => {
                    const elapsed = Date.now() - started;
                    const msg = `${req.method} "${req.urlWithParams}"
             ${ok} in ${elapsed} ms.`;
                    console.log(msg);
                    // this.messenger.add(msg);
                    if (`${ok}` === 'failed') {
                        Zero3LayoutNavbarComponent.RES_STATUS = 400;
                    } else {
                        Zero3LayoutNavbarComponent.RES_STATUS = 200;
                    }
                })
            );
    }
}
